// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// J [author] rhyme_lph
// n [email]  rhymelph@gmail.com
// g [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/employee_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/contact/employee_contacts_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
export 'package:finance_app/src/entities/employee_contact_entity.dart';

@RouterMeta(paramName: "employeeContactsPage")
class EmployeeContactsPage extends StatefulWidget {
  final List<EmployeeContactEntity> employees;
  final EmployeeContactEntity select;
  final bool canAdd;
  final bool showAll;

  const EmployeeContactsPage(
      {Key key, this.employees, this.select, this.canAdd, this.showAll})
      : super(key: key);

  @override
  _EmployeeContactsPageState createState() => _EmployeeContactsPageState();
}

class _EmployeeContactsPageState extends State<EmployeeContactsPage>
    with PagePresenter<EmployeeContactsPage, EmployeeContactsProvider> {
  @override
  void initState() {
    provider.currentSelectContact = widget.select;
    provider.isShowAll = widget.showAll;
    provider.useLocalData = widget.employees != null;
    provider.data = widget.employees;
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.employee,
      );

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            if (widget.canAdd != false)
              NormalFormWrapper(
                child: listBuilder<String>(
                  selector: (_, __) => __.searchController.text,
                  builder: (BuildContext context, String value, Widget child) =>
                      buildSearchWidget().length == 0 && value.length > 0
                          ? AddButton(
                              title: '${S.current.add} “$value”',
                              onTap: provider.onAddEmployee,
                            )
                          : AddButton(
                              title: S.current.add_employee,
                              onTap: provider.onShowAddEmployee,
                            ),
                ),
              )
            else
              AppSpaces.h20,
            Expanded(child: super.buildEmptyWidget),
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            if (widget.canAdd != false)
              NormalFormWrapper(
                child: listBuilder<String>(
                  selector: (_, __) => __.searchController.text,
                  builder: (BuildContext context, String value, Widget child) =>
                      buildSearchWidget().length == 0 && value.length > 0
                          ? AddButton(
                              title: '${S.current.add} “$value”',
                              onTap: provider.onAddEmployee,
                            )
                          : AddButton(
                              title: S.current.add_employee,
                              onTap: provider.onShowAddEmployee,
                            ),
                ),
              )
            else
              AppSpaces.h20,
            Expanded(
              child: listBuilder<Map<String, List<EmployeeContactEntity>>>(
                selector: (_, __) =>
                    Map<String, List<EmployeeContactEntity>>.from(__.groupMap),
                builder: (BuildContext context,
                        Map<String, List<EmployeeContactEntity>> value,
                        Widget child) =>
                    CustomScrollView(
                  slivers: buildSearchWidget(),
                ),
              ),
            ),
          ],
        ),
      );

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<EmployeeContactEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<EmployeeContactEntity> data, int i) {
    return listBuilder<EmployeeContactEntity>(
        selector: (_, __) => __.currentSelectContact,
        builder: (BuildContext context, EmployeeContactEntity value,
                Widget child) =>
            PressedOpacityButton(
              onPressed: () => provider.onSelectEmployeeContact(data[i]),
              padding: EdgeInsets.symmetric(
                horizontal: getDp(29),
                vertical: getDp(21),
              ),
              border: data.length == i + 1
                  ? null
                  : Border(
                      bottom:
                          BorderSide(color: aceGrayColor, width: getDp(0.5))),
              color: value?.id == data[i]?.id
                  ? aceSelectBackgroundColor
                  : Colors.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  EmployeeRadio(
                    isSelect: value?.id == data[i]?.id,
                    title: data[i].name,
                    content: data[i].title ?? S.current.normal,
                  ),
                ],
              ),
            ));
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
